package com.cjk.foundation.commons.mvc;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.cjk.foundation.commons.BusinessException;
import com.cjk.foundation.commons.response.Response;

public class ExceptionResolver implements HandlerExceptionResolver {
	private static final Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		int status = 500;
		String result = "";
		try {
			logger.error(ex.getMessage());
			throw ex;
		} catch (BindException e) {
			status = 400;
			result = JSON.toJSONString(Response.error("不合法请求"));
		} catch (BusinessException e) {
			status = 200;
			result = JSON.toJSONString(Response.error(e.getMessage()));
		} catch (Exception e) {
			e.printStackTrace();
			result = JSON.toJSONString(Response.error("系统异常:" + e.getMessage()));
		}
		response.setStatus(status);
		response.setContentType("application/json;charset=utf-8");
		try {
			response.setContentLength(result.getBytes("utf8").length);
			response.getWriter().write(result);
//			PrintWriter writer = response.getWriter();
//			writer.print(result);
//			writer.flush();
//			writer.close();
		} catch (IOException e) {
			logger.error("an unknown error occurred while writting repsonse data", e);
		}
		return new ModelAndView();
	}

}
